<?php
header("Content-type: text/html; charset=utf-8");
$js=json_decode($_REQUEST["hook"]);//json转换


$projectArray = array(
    "123" => array(
    	"name" => "projectname",
    	"path" => 'PATH=$PATH:/usr/local/git/bin && cd /data/wwwroot/githooktest/githooktest/',
    	"origin" => "master",
    	"release" => "release",
    	"shell" => ""
    ),
    "1234" => array(
    	"name" => "projectname1",
    	"path" => 'PATH=$PATH:/usr/local/git/bin && cd /data/wwwroot/githooktest1/githooktest1/',
    	"origin" => "master",
    	"release" => "release",
    	"shell" => ""
    )
);

if( $projectArray[$js->password]['name']=='' )die("ERROR!");

$lastcommit=$js->push_data->commits[count($js->push_data->commits)-1];//获取最后的commit

date_default_timezone_set('PRC');
$dateYmd = date("Y-m-d");
$fp=fopen("./log/log-{$projectArray[$js->password]['name']}-{$dateYmd}.log",'a');

//这里意为：如果最后的commit包含"release"则进行自动发布>。
if(strstr($lastcommit->message,$projectArray[$js->password]['release'])){
	$info = array();
	$info_1 = $info_2 = 0;

	$shellPath = $projectArray[$js->password]['path'];

	$shell_1 = $shell_2 = $shellPath;
	$shell_1 .= ' && git fetch --all';
	$shell_1 .= ' || git reset --hard origin/'.$projectArray[$js->password]['origin'];

	$shell_2 .= ' && git pull origin '.$projectArray[$js->password]['origin'];

	exec( $shell_1,$info[1],$info_1 );
	exec( $shell_2,$info[2],$info_2 );
	exec( $projectArray[$js->password]['shell'] );

	/*
	echo '<pre>';
	print_r( $info );
	echo $info_1;
	echo $info_2;
	*/
	$infoJson = json_encode($info);
    if( $info_2 == 0 && $info[2][0] != 'Already up-to-date.' ){
    	fwrite($fp,"T".date('Y-m-d H:i:s')."\t".$lastcommit->message."\t".$lastcommit->author->name."\n");
    }else{
    	fwrite($fp,"F".date('Y-m-d H:i:s')."\t".$lastcommit->message."\t".$lastcommit->author->name."\t".$infoJson."\n");
    }
	//file_put_contents("test.txt", $infoJson."\r\n\r\n", FILE_APPEND);

}else{
	//fwrite($fp,'N'.date('Y-m-d H:i:s')."\t".$lastcommit->message."\t".$lastcommit->author->name."\n");
}